<template>
  <div class="register">
    <div class="decr">
      <div class="imgP">
        <img src="../../assets/好大一只.png" alt="Logo" />
      </div>
      <div class="content">
        <h1>Hi~</h1>
        <section>
          这是一个初创公司，在这个公司里，我们希望通过自己的努力，帮助更多的人。
        </section>
      </div>
    </div>
    <div class="register-box">
      <h3>欢迎注册!</h3>
      <form action="register">
        <div class="input-box">
          <label for="email">邮&emsp;&emsp;箱：</label>
          <input
            type="email"
            name="email"
            id="email"
            v-model="fromParam.email"
            placeholder="请输入邮箱~"
          />
        </div>
        <div class="input-box">
          <label for="code">验&ensp;证&ensp;码：</label>
          <div class="code_box">
            <input
              type="text"
              id="code"
              v-model="fromParam.code"
              maxlength="6"
              placeholder="请输入6位验证码~"
            />
            <el-button
              type="button"
              class="code-button"
              :disabled="isButtonDisabled"
              @click="sendCode"
            >
              {{ countdown > 0 ? countdown + "秒后重发" : "发送验证码" }}
            </el-button>
          </div>
        </div>
        <div class="input-box">
          <label for="password">密&emsp;&emsp;码：</label>
          <input
            type="password"
            id="password"
            v-model="fromParam.password"
            placeholder="请输入登录密码~"
          />
        </div>
        <div class="input-box">
          <label for="repassword">确认密码：</label>
          <input
            type="password"
            id="repassword"
            v-model="fromParam.repassword"
            placeholder="请输入确认密码~"
          />
        </div>
      </form>
      <div class="infobox">
        <el-checkbox v-model="userDeal" @change="toggleCheck">
          <!--el 弹窗内容 -->
          <span>用户注册协议</span>
          <el-dialog
            title="用户注册协议"
            :visible="userDeal"
            width="30%"
          ></el-dialog>
        </el-checkbox>
        <router-link class="link" to="/forgot">忘记密码</router-link>
        <router-link class="link" to="/login">前往登录</router-link>
      </div>
      <button type="submit" class="register-button" @click="registerFun">
        注册
      </button>
    </div>
  </div>
  <footer class="footer">
    <a href="https://beian.miit.gov.cn/" target="_blank">
      备案号: 蜀ICP备2024086875号-1
    </a>
    <div>
      <a
        href="https://www.douyin.com/user/MS4wLjABAAAAJxUIX2GMq0-rcucksrrllJj93HHnceibxk40_PWmeX0"
        target="_blank"
        >© 好大一只</a
      >
    </div>
  </footer>
</template>

<script setup lang="ts">
import { ref, watch, onUnmounted, onMounted } from "vue";
import { SendEmailCodeParams, RegisterParams } from "../../types/user";

import { sendEmailCode, registerApi } from "../../api/auth";

import { ElMessage } from "element-plus";
import router from "../../router";

const countdown = ref(0);
const isButtonDisabled = ref(false);
let countdownInterval: string | number | NodeJS.Timeout | undefined;
let fromParam = ref<RegisterParams>({
  username: "好大一只",
  age: 24,
  code: "",
  // "birth": "2000-02-20",
  // "gender": "男",
  // "signature": "This is a test signature",
  // email: "3438345207@qq.com",
  email: "",
  password: "",
  // password: "123456",
  repassword: "",
  // "cellphone": "1234567890",
  // "avatarURL": "http://example.com/avatar.jpg",
  // "createAt" : "2022-02-12 12:45:12"
});

// 定义一个响应式变量来存储用户选择的值
const userDeal = ref(false);

// 定义一个方法来处理值变化
function toggleCheck(value: boolean) {
  if (value) {
    console.log("用户已阅读并同意用户注册协议");
  } else {
    console.log("用户取消了对用户注册协议的同意");
  }
}

const updateCountdown = () => {
  if (countdown.value > 0) {
    countdown.value -= 1;
    localStorage.setItem("countdown_reg", countdown.value.toString());
  } else {
    isButtonDisabled.value = false;
    localStorage.removeItem("countdown_reg");
    localStorage.removeItem("codeExpiryTime_reg"); // 清除过期时间
    clearInterval(countdownInterval);
  }
};
const sendCode = async () => {
  // 校验手机号或邮箱是否为空
  if (fromParam.value.cellphone === "" && fromParam.value.email === "") {
    ElMessage.error("手机号或邮箱不能为空");
    return;
  }

  try {
    // 发送验证码的请求
    let sendEamilCodeParams: SendEmailCodeParams = {
      email: fromParam.value.email,
      cellPhone: fromParam.value.cellphone,
      mode: "register",
    };
    const response = await sendEmailCode(sendEamilCodeParams);

    if (response.code !== 200) {
      ElMessage.error(response.message);
      return;
    }

    ElMessage.success("发送成功");

    // 启动倒计时
    countdown.value = 60; // 设置倒计时时间为60秒
    isButtonDisabled.value = true;

    // 存储过期时间
    const codeExpiryTime = Date.now() + countdown.value * 1000;
    localStorage.setItem("countdown_reg", countdown.value.toString());
    localStorage.setItem("codeExpiryTime_reg", codeExpiryTime.toString());

    // 清除之前的倒计时
    clearInterval(countdownInterval);
    countdownInterval = setInterval(updateCountdown, 1000);
  } catch (error) {
    ElMessage.error("发送失败");
    // 不启动倒计时
    countdown.value = 0;
    isButtonDisabled.value = false;
  }
};

onUnmounted(() => {
  clearInterval(countdownInterval);
});
// 页面加载时初始化倒计时
onMounted(() => {
  const savedCountdown = parseInt(
    localStorage.getItem("countdown_reg") || "0",
    10
  );
  const codeExpiryTime = parseInt(
    localStorage.getItem("codeExpiryTime_reg") || "0",
    10
  );
  const now = Date.now();

  // 如果倒计时未过期
  if (savedCountdown > 0 && now < codeExpiryTime) {
    countdown.value = Math.ceil((codeExpiryTime - now) / 1000); // 计算剩余秒数
    isButtonDisabled.value = true;
    countdownInterval = setInterval(updateCountdown, 1000);
  } else {
    // 重置倒计时数据
    localStorage.removeItem("countdown_reg");
    localStorage.removeItem("codeExpiryTime_reg");
  }
});
watch(countdown, (newVal) => {
  if (newVal <= 0) {
    isButtonDisabled.value = false;
  }
});

const registerFun = async () => {
  // 校验手机号或邮箱是否为空
  if (fromParam.value.email === "") {
    ElMessage.error("手机号或邮箱不能为空");
    return;
  }
  // 验证码不能为空
  if (fromParam.value.code === "" && fromParam.value.code.length >= 6) {
    ElMessage.error("验证码不正确");
    return;
  }
  // 校验密码
  if (fromParam.value.password !== fromParam.value.repassword) {
    ElMessage.error("两次密码不一致");
    return;
  }
  // 生成随机用户名字符

  fromParam.value.username = "USER_" + Math.random().toString(36).substr(2);
  // 年龄
  fromParam.value.age = 0;

  const response = await registerApi(fromParam.value);
  if (response.code !== 200) {
    ElMessage.error("注册失败");
    return;
  }
  ElMessage.success("注册成功");
  // 跳转到登录页面
  router.push("/login");
};
</script>

<style lang="scss" scoped>
.register {
  // min-height: 100%;
  height: 100%;
  width: 100%;
  background: linear-gradient(to right, #a7e4f1 20%, #81cfe0 50%, #0083b0 80%);
  display: flex;
  justify-content: space-between;
  align-items: center;

  .decr {
    height: 100%;
    width: 60%;
    background-color: antiquewhite;
    opacity: 0.8;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 20px;

    .imgP {
      img {
        width: 100%;
        max-width: 300px;
        margin-bottom: 20px;
      }
    }

    .content {
      text-align: center;

      h1 {
        font-size: 2.5rem;
        color: #333;
        margin-bottom: 10px;
      }

      section {
        font-size: 1.25rem;
        color: #0083b0;
      }
    }
  }

  .register-box {
    flex: 1;
    max-width: 400px;
    padding: 20px;
    background-color: #f9f9f9;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    margin: 50px auto;
    text-align: left;
    display: flex;
    flex-direction: column;
    justify-content: center;

    h3 {
      text-align: center;
      margin-bottom: 20px;
      color: #333;
      font-size: 1.5rem;
    }

    form {
      .input-box {
        margin-bottom: 15px;
        display: flex;
        align-items: center;

        label {
          flex: 0 0 80px; /* 控制 label 的固定宽度 */
          margin-right: 10px;
          color: #555;
        }

        input {
          flex: 1;
          padding: 10px;
          border: 1px solid #ddd;
          border-radius: 4px;
          outline: none;

          &:focus {
            border-color: #66afe9;
            box-shadow: 0 0 8px rgba(102, 175, 233, 0.6);
          }
        }
        .code_box {
          display: flex;
          justify-content: space-between;
          align-items: center;
          #code {
            width: 30%;
            margin-right: 10px;
          }
          .code-button {
            height: 100%;
            background-color: #409eff;
            border-radius: 4px;
            color: white;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s;

            &:hover {
              background-color: #66b1ff;
            }

            &:disabled {
              background-color: #ddd;
              cursor: not-allowed;
            }
          }
        }
      }
    }

    .infobox {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .el-checkbox {
        flex-shrink: 0;
      }

      .link {
        color: #409eff;
        cursor: pointer;
        transition: color 0.3s;

        &:hover {
          color: #66b1ff;
        }
      }
    }

    .register-button {
      width: 100%;
      padding: 10px;
      background-color: #409eff;
      border: none;
      border-radius: 4px;
      color: white;
      font-size: 16px;
      cursor: pointer;
      transition: background-color 0.3s;

      &:hover {
        background-color: #66b1ff;
      }
    }
  }

  @media (max-width: 768px) {
    flex-direction: column;
    .decr {
      display: none; // 小屏幕时隐藏描述部分
    }

    .register-box {
      width: 90%;
      margin: 20px auto;
      padding: 20px;
    }
  }
}
</style>
